import psutil
from bytestohuman import bytes2human
import time,os

BFH = r'%'


def getProcessInfo(process_nums):
    """
    getProcessInfo[0][0]: Process name
    getProcessInfo[0][1]: Process PID
    getProcessInfo[0][2]: Process status
    getProcessInfo[0][3]: Process Mem percent
    getProcessInfo[0][4]: Process Mem value
    getProcessInfo[0][5]: Process Creation time
    getProcessInfo[0][6]: Process Cpu usage rate
    getProcessInfo[1]   : Total Process numbers
    :param process_nums:函数按照降序返回的进程数量
    :return:
    """
    try:
        process_info = []
        for i in psutil.pids():
            try:
                pid_info = []
                pid_info.append(psutil.Process(i).name())  # Process name
                pid_info.append(i)  # Process PID
                pid_info.append(psutil.Process(i).status())  # Process working status
                pid_info.append(psutil.Process(i).memory_percent())  # Process Mem percent
                pid_info.append(psutil.Process(i).memory_info().rss)  # Process Mem value
                pid_info.append(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(
                    psutil.Process(i).create_time())))  # Process CPU creation time
                process_info.append(pid_info)
            except:
                # 如果出现进程不存在，则跳过这个进程，继续循环
                continue

        p=sorted(process_info, key=lambda pid: pid[4], reverse=True)
        final_process = []
        display_line_nums = 0
        while display_line_nums < process_nums:
            try:
                p[display_line_nums].append(psutil.Process(p[display_line_nums][1]).cpu_percent(interval=0.1))
                final_process.append(p[display_line_nums])
                display_line_nums+=1
            except:
                continue
        return [final_process,len(p)]
    except:
        pass


if __name__ == "__main__":
    while True:
        try:
            time.sleep(1)
            if os.name == 'nt':
                os.system("cls")
            else:
                os.system("clear")

            print(" %-35s %8s %-8s %9s %15s %23s" % ("Process name", "PID",
                                                     "STATUS",
                                                     "CPU %",
                                                     "MEM",
                                                     "Creation Time"))
            print(
                "--------------------------------------------------------------------------------------------------------")
            for i in getProcessInfo(10)[0]:
                print(" %-35s %8s %-8s %8.2f%s %15s %23s"
                      % (i[0], i[1], i[2], i[6], BFH, (str("%5.2f" % i[3]) + "%|" + str(bytes2human(i[4]))), i[5]
                         )
                      )

            print(
                "--------------------------------------------------------------------------------------------------------")
        except Exception as e:
            print(e)


